<template>
    <view class="xilu">
        <view class="page-foot bg-white" @click="formSubmit()">
            <view class="btn1">确定提交</view>
        </view>
        <view class="container pt30 plr30">
            <view class="xilu_status p30 mb20"v-for="(item,index) in order.order_product" >
                <view class="flex-box">
                    <image :src="item.image" class="xilu_pic" mode="aspectFill"></image>
                    <view class="flex-grow-1">
                        <view class="m-ellipsis-l2 fs30 col10 mb50">{{item.product_name}}</view>
                        <view class="red fs40 "><text class="fs24">¥</text><text class="fwb">{{item.sum_price}}</text></view>
                    </view>
                </view>
            </view>
            <view class="xilu_status p30 mb20">
                <view class="fs34 col10 pb20 fwb">申请信息</view>
                <picker @change="changeType" :value="typeIndex" :range="types" range-key="name">
                    <view class="flex-box flex-between m-arrow-right mb30">
                        <view class="fs30 col5">申请类型</view>
                        <view>{{typeIndex===''?'请选择':types[typeIndex].name}}</view>
                    </view>
                </picker>
                <picker @change="changeExpressType" :value="expressTypeIndex" :range="expressType" range-key="name">
                    <view class="flex-box flex-between m-arrow-right mb30">
                        <view class="fs30 col5">货物状态</view>
                        <view>{{expressTypeIndex===''?'请选择':expressType[expressTypeIndex].name}}</view>
                    </view>
                </picker>
                <picker @change="changeReason" :value="reasonIndex" :range="reasons" range-key="name">
                    <view class="flex-box flex-between m-arrow-right mb30">
                        <view class="fs30 col5">申请原因</view>
                        <view>{{reasonIndex===''?'请选择':reasons[reasonIndex].name}}</view>
                    </view>
                </picker>
                <view class="flex-box flex-between mb30">
                    <view class="fs30 col5">退款金额</view>
                    <view class="fs30 red"><text class="fs24">¥</text>{{order.total_price}}</view>
                </view>
                <view class="fs30 col5 pb30">申请说明</view>
                <textarea cols="30" rows="10" class="xilu_textarea" v-model="aftersale.refund_content" placeholder="请详细填写申请说明" placeholder-class="cola"></textarea>
                <view class="fs30 col5 pb30">上传图片</view>
                <u-upload :fileList="fileListimages" @afterRead="afterRead" @delete="deletePic" name="images" multiple :maxCount="10" width="200" height="200" :previewFullImage="true"></u-upload>
            </view>
        </view>
    </view>
</template>

<script>
	var validate = require("../../xilu/validate.js");
    export default {
        data() {
            return {
				order:{},
				expressType:[],
				expressTypeIndex:'',
                types: [],
                typeIndex: "",
				reasons:[],
				reasonIndex:'',
                fileListimages: [],
				aftersale:{
					refund_content:''
				}
            };
        },
		onLoad(options) {
			let page = this;
			// this.getOpenerEventChannel().on('refundTransfor',function(order){
			// 	page.fetchOrder(order.id);
			// })
			page.fetchOrder(options.id)
			this.fetchConfig();
			
		},
        methods: {
			//基础配置
			fetchConfig(){
				this.$core.get({url:'xilumarket.common/aftersale_config',data:{},loading:false,success:ret=>{
					this.expressType = ret.data.express_type;
					this.types = ret.data.type;
					this.reasons = ret.data.reason
				}})
			},
			fetchOrder(orderId){
				this.$core.get({url:'xilumarket.order/aftersale_goods',data:{order_id:orderId},loading:false,success:ret=>{
					this.order = ret.data;
				}})
			},
			changeExpressType(e) {
			    this.expressTypeIndex = e.detail.value
			},
            changeType(e) {
                this.typeIndex = e.detail.value
            },
			changeReason(e) {
			    this.reasonIndex = e.detail.value
			},
            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`fileList${event.name}`].length
                lists.map((item) => {
                    this[`fileList${event.name}`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
            },
            uploadFilePromise(filepath) {
            	let page = this;
                return new Promise((resolve, reject) => {
            		page.$core.uploadFile({
            			filePath: filepath,
            			success: (ret, response) => {
            				 resolve(ret.data.url)
            			}
            		})
                })
            },
			//提交
			formSubmit() {
			    let formData = this.aftersale;
				formData.order_id = this.order.id;
				formData.order_product_id = this.order.order_product[0].id;
				formData.price = this.order.total_price;
				formData.express_type = this.expressTypeIndex !== ''?this.expressType[this.expressTypeIndex].id:'';
				formData.type = this.typeIndex !== ''?this.types[this.typeIndex].id:'';
				formData.reason = this.reasonIndex !== ''?this.reasons[this.reasonIndex].name:'';
				console.log(formData);
				let images = []
				this.fileListimages.forEach(item=>images.push(item.url));
				formData.images = images.join(',');
			    var rule = [
					{name: 'order_id',nameChn: '订单ID',rules: ['require','gt:0'],errorMsg: {require: '订单错误',gt: '订单错误'},},
					{name: 'order_product_id',nameChn: '商品id',rules: ['require','gt:0'],errorMsg: {require: '商品错误',gt: "商品错误"},},
					{name: 'type',nameChn: '售后类型',rules: ['egt:0'],errorMsg: {egt: '请选择售后类型'},},
					{name: 'express_type',nameChn: '物流状态',rules: ['egt:0'],errorMsg: {egt:'请选择物流状态'},},
					
					{name: 'reason',nameChn: '售后原因',rules: ['require'],errorMsg: {require: '请选择售后原因'},},
					{name: 'refund_content',nameChn: '退款说明',rules: ['require','length:1,600'],errorMsg: {require: '请填写申请说明',length: "说明限制600字"},},
					];
			    // 是否全部通过，返回Boolean
				//console.log(validate.check(formData,rule),validate.getError(),formData);
			
				if(!validate.check(formData,rule)){
					uni.showToast({title: validate.getError()[0],icon:'none'});
					return ;
				}
				this.$core.post({url:'xilumarket.aftersale/apply_aftersale',data:formData,success:ret=>{
					this.getOpenerEventChannel().emit('aftersaleSuccess',ret.data);
					uni.navigateBack({});
					uni.showToast({title: ret.msg,icon:'none'});
				}})
			}
			
		}
    }
</script>

<style lang="scss" scoped>
    .xilu {
        .container {
            background: #f7f9fc;
        }

        &_status {
            background-color: var(--white);
            box-shadow: 0rpx 4rpx 20rpx 5rpx rgba(183, 189, 202, 0.05);
            border-radius: 20rpx;
        }

        &_pic {
            width: 180rpx;
            height: 180rpx;
            border-radius: 10rpx;
            margin-right: 30rpx;
        }

        .m-arrow-right::after {
            border-color: #000000;
        }

        &_textarea {
            width: 100%;
            height: 260rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 30rpx;
            margin-bottom: 50rpx;
        }


    }
</style>
